// pages/bdmap/bdmap.js
var L = require('../../components/zhgeo/leafletwx')
import {createMap} from '../../components/zhgeo/base.map'
let Lmap,mapType,tif,gj,markers=[],markersGroup
const app = getApp() //app.globalData

Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectIndex:0,
    areaIndex:0,
    areaArray:['武汉城市圈','长江经济带','全国'],
    list1:['AQI','PM2.5','PM10','NO2','SO2','O3','CO'],
    list2:['风向','风力','温度','湿度','压强','天气'],
    btnIndex:0,
    mapIndex:0,
    mapUrlList:[
      'http://webrd03.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
      'https://api.mapbox.com/styles/v1/zsy20/cl65rhsth001114tii4zkniny/draft/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoienN5MjAiLCJhIjoiY2w2NXI5N3pjMzNpbTNqbW41ZGJoOXQydyJ9.topH2zrogcYOf1s1jBtpnQ',
      'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'
    ],
    isShowMapList:false,
    funList:[true,false,false,true],
    areaLIist:[ 'https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/json/1%2B8.geojson','https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/json/Yangtze.geojson','https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/json/china.json'],
    cityName:'',
  
  },
  // 空气/气象参数切换
  changeIndex(e) {
    let index = e.currentTarget.dataset.item
    this.setData({
      selectIndex:index,
      btnIndex:0,
    })
  },
  // 范围切换
  changeAreaIndex(e) {
    this.setData({
      areaIndex:e.detail.value
    })
    if(gj)gj.remove();
    this.addShp(this.data.areaLIist[this.data.areaIndex])
    switch (e.detail.value) {
      case '1':
        Lmap.setView([29.500991, 109.005], 4)
        break;
      case '2':
        Lmap.setView([40.000991, 106.338728], 3)
        break;
      default:
        Lmap.setView([31.1, 114.332314],7)
        break;
    }
    if(this.data.funList[0]){
      if(tif)tif.remove();
      this.addWms()

    }
  },
  changeCityName(e) {
    this.setData({
      cityName:e
    })
  },
  // 添加shp
  addShp(url) {
    wx.request({
      url: url,
      success (res) {
        gj = L.geoJSON(res.data,
          {
            style: function(feature) {
              return {
              color: "#3388ff",
              fill: true,
              fillOpacity: 0.02,
              weight: 1,
              };
            }
          }
        ).addTo(Lmap)
      },
      fail (err) {
        console.log(err)
      }
    })
  },
  // 信息选择   
  changeBtnIndex(e) {
    let index = e.currentTarget.dataset.item
    
    this.setData({
      btnIndex:index,
    })
    this.stationTips()
  },
//   点击站点显示数据
  stationTips() {
    let msgName, unit
    if (this.data.selectIndex == 0) {
      unit = 'µg/m³'
      switch (this.data.btnIndex) {
        case 0:
          msgName = 'aqi'
          break;
        case 1:
          msgName = 'pm25'
          break;
        case 2:
          msgName = 'pm10'
          break;
        case 3:
          msgName = 'no2'
          break;
        case 4:
          msgName = 'so2'
          break;
        case 5:
          msgName = 'o3'
          break;
        case 6:
          msgName = 'co'
          unit = 'mg/m³'
          break;
      }
    }else {
      switch (this.data.btnIndex) {
        case 0:
          msgName = 'wind_d'
          break;
        case 1:
          msgName = 'wind_p'
          break;
        case 2:
          msgName = 'temperature'
          break;
        case 3:
          msgName = 'humidity'
          break;
        case 4:
          msgName = 'pressure'
          break;
        case 5:
          msgName = null
          break;
      }
    }
    markers.map(e => {
      e.bindPopup(() => {
        this.changeCityName(e.city)
        return  msgName? (e[msgName]+unit):'暂无数据'
      })
    })
  },
  // 添加站点
  addStation() {
    let areaType,iconUrl
    let list = ['wuhanCC','yangtzeRiverEB','china']
    if(this.data.funList[3]){
      markers = []
      switch(this.data.selectIndex) {
        case 0:
          areaType = list[this.data.areaIndex]
          iconUrl = 'https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/map/airIcon.png'
          break;
        case 1:
          iconUrl = 'https://7072-prod-0g6d813n9889e2e6-1322465086.tcb.qcloud.la/map/mete.png'
          areaType = 'wuhanCC'
          break;
      }
      app.globalData.http.get('/ai-sensing-back-service/api/publishData/getStationData',{
        area: areaType,//wuhanCC,yangtzeRiverEB,china
        type: this.data.selectIndex == 0 ?'air' : 'weather',
        time: (this.data.selectIndex == 1  || this.data.areaIndex == 1)?'2023-05-09 00:00:00':''
      }).then(res=>{
        res.data.list.map(e=>{
          let marker = L.marker([e.lat,e.lng], {
            src: iconUrl,
            width: 25,
            height: 25,
            showInCenter: false,
          });
          if(this.data.selectIndex == 0) {
            switch (this.data.areaIndex) {
              case 0:
                marker.pm25 = e.pm25onehour
                marker.pm10 = e.pm10onehour
                marker.no2 = e.no2onehour
                marker.so2 = e.so2onehour
                marker.o3 = e.o3onehour
                marker.co = e.coonehour
                marker.aqi = e.aqi
                marker.city = e.stationname
                break;
              default:
                marker.aqi = e.aqi
                marker.co = e.co
                marker.no2 = e.no2
                marker.o3 = e.o3
                marker.pm25 = e.pm2_5
                marker.pm10 = e.pm10
                marker.name = e.position_name
                marker.so2 = e.so2
                marker.city = e.position_name
                break;
            }
          }else {
            marker.city = e.city
						marker.pressure = e.pressure
						marker.humidity = e.humidity
						marker.temperature = e.temperature
						marker.wind_d = e.wind_d
						marker.wind_p = e.wind_p
          }
          
          markers.push(marker)
  
        })
        
        markersGroup = L.layerGroup(markers)
        markersGroup.addTo(Lmap)
        
        this.stationTips()
      })
    }else {
      Lmap.removeLayer(markersGroup)
    }
    
  },
  // 切换地图
  changeMapIndex(e) {
    let index = e.currentTarget.dataset.item
    let url = this.data.mapUrlList[index]
    this.setData({
      mapIndex:index,
    })
    mapType.remove()
    mapType = L.tileLayer(url).addTo(Lmap)
  },
  showMapList(e) {
    this.setData({
      isShowMapList:true
    })
  },
  closeMapList(e) {
    this.setData({
      isShowMapList:false
    })
  },

  // 功能按钮
  changeFunIndex(e) {
    let index = e.currentTarget.dataset.item
    let list = this.data.funList
    list[index] = !list[index]
    this.setData({
      funList:list,
    })
    switch (index) {
      case '0':
        this.showPM()
        break;
      case '3':
        this.addStation()
        break;
    }
  },
  // 加载wms
  showPM() {
    let boolean = this.data.funList[0]
    if(boolean) {
      this.addWms()
    }else{
      if(tif)tif.remove();
    }
  },
  addWms() {
    app.globalData.http.get('/ai-sensing-back-service/product/getLayerByType',{
      type: 'PM2.5产品',
      area: this.data.areaArray[this.data.areaIndex]
    }).then(res=>{
      let data = res.data[0]
      let list = data.path.split(':')
      tif = L.tileLayer.wms('http://ai-ecloud.whu.edu.cn/geoserver/'+list[0]+'/wms?',
      {
        layers: list[1],
        format: 'image/png',
        transparent: true,
        styles: data.style
      })
      tif.addTo(Lmap);
    })

  },
  // 重置位置 
  setSite() {
    switch (this.data.areaIndex) {
      case '1':
        Lmap.setView([29.500991, 109.005], 4)
        break;
      case '2':
        Lmap.setView([40.000991, 106.338728], 3)
        break;
      default:
        Lmap.setView([31.1, 114.332314],7)
        break;
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    const container = this.selectComponent('#leafletwx')
    let min_zoom =  2
    let max_zoom = 18
    createMap(container,  {
        minZoom: min_zoom,
        maxZoom: max_zoom,
      }, function(map) {
      // L.tileLayer('https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}').addTo(map)

      mapType = L.tileLayer('http://webrd03.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}')

      mapType.addTo(map)
      map.on('zoomend', (e) => {
        //获取当前放大或者缩小的等级
      });
      that.addShp(that.data.areaLIist[that.data.areaIndex])
      map.setView([31.1, 114.332314],7)
      Lmap = map
      that.showPM()
      that.addStation()
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})